package com.wulis.common.converter;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.Collection;
import java.util.List;

/**
 * Orika 工具类
 *
 * @author wulibao
 */
public class MapperConvert {

    /**
     * MAPPER_FACTORY: 使用MapperFactory作为单例 其中一个的最昂贵件Orika的是实例化和MapperFactory的初始化，这是从它得到的MapperFacade。MapperFactory和
     * MapperFacade是线程安全的对象，可以安全地在您自己的代码中作为单例共享。
     */
    private final static MapperFactory FACTORY = new DefaultMapperFactory.Builder().build();

    private final static MapperFacade FACADE;

    /*
     * 构建双向映射
     */
    static {
        ConverterFactory converterFactory = MapperConvert.FACTORY.getConverterFactory();
        converterFactory.registerConverter(new DateTypeConverter());
        FACADE = FACTORY.getMapperFacade();
    }

    public static MapperFacade getFacade() {
        return FACADE;
    }

    public static MapperFactory getFactory() {
        return FACTORY;
    }

    public static <S, D> D map(S sourceObject, Class<D> destinationClass) {
        return FACADE.map(sourceObject, destinationClass);
    }

    public static <S, D> List<D> batchMap(Collection<S> collection, Class<D> destinationClass) {
        return collection.stream().map(sourceObject -> map(sourceObject, destinationClass)).toList();
    }

}
